﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace ceTerm
{
    public partial class XForm : Form, AT_UHF_NET.IUHFHost, ATScan_NET.IScan
    {

        public enum Action
        {
            IDLE,
            Write,
            SetPower
        };

        public Action action = Action.IDLE;

        public enum barkodTipleri
        {
            Top = '0',
            RafAraba = '1',
            CikisEmri = '2',
            GelisPartisi = '3',
            Tanimsiz
        }

        public XForm()
        {
            InitializeComponent();

            this.WindowState = FormWindowState.Maximized;
            lKisa.Click += new EventHandler(lKisa_Click);
            lUzun.Click += new EventHandler(lUzun_Click);
            lRFID.Click += new EventHandler(lRFID_Click);
            lDetay.Click += new EventHandler(lDetay_Click);

            this.Closing += new System.ComponentModel.CancelEventHandler(XForm_Closing);
            power.ValueChanged += new EventHandler(power_ValueChanged);
            //idleTimer.Interval = idleTimeoutMs;
            //idleTimer.Tick += new EventHandler(idleTimer_Tick);
            //idleTimer.Enabled = false;
        }

        public virtual void lDetay_Click(object sender, EventArgs e)
        {
        }

        void XForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!Settings.IsInDebugMode)
            {
                Terminal.StopBarcode();
                Terminal.StopRFID();
            }
        }

        void lRFID_Click(object sender, EventArgs e)
        {
            bool open = (lRFID.BackColor == SystemColors.Control);  //next state, not current!
            if (open)
                action = Action.SetPower;

                //Terminal.RFID.SET_PowerControl((uint)power.Value);

            Terminal.StopRFID();
            lRFID.BackColor = (open ? Color.Gray : SystemColors.Control);
            lKisa.Visible = lUzun.Visible = open;
        }

        void lUzun_Click(object sender, EventArgs e)
        {
            lKisa.BackColor = SystemColors.Control;
            lUzun.BackColor = Color.Gray;
            power.Value = (uint)Settings.Power.OkumaMax;    //0;
        }

        void lKisa_Click(object sender, EventArgs e)
        {
            lUzun.BackColor = SystemColors.Control;
            lKisa.BackColor = Color.Gray;
            power.Value = (uint)Settings.Power.OkumaMin;    //10
        }


        #region IUHFHost Members

        public virtual void GetAccessEPC(string EPC)
        {
        }

        public virtual void GetMemoryData(string MemoryData)
        {
        }

        public virtual void GetReply(string Reply)
        {
            switch (action)
            {
                case Action.SetPower:
                    Terminal.RFID.SET_PowerControl((uint)power.Value);  //return value is the power set.
                    Terminal.StartRFID();
                    break;

                default:
                    break;
            }
            action = Action.IDLE;
        }

        #endregion

        #region IScan Members

        public virtual void OnScaned(string BarcodeValue, string TypeName, string TypeID)
        {
        }

        #endregion

        public static void Browse(string URL, bool IsLocalAddress, string Header)
        {
            WebBrowser wb = new WebBrowser(Settings.WebServiceURL.Replace("/ceTerminal.asmx", "/" + URL), false, Header);
            //WebBrowser wb = new WebBrowser(URL, IsLocalAddress, Header);
            wb.ShowDialog();
        }

        public static void SetButtonsStatus(Form form, bool enabled)
        {
            foreach (Control ctrl in form.Controls)
                if (ctrl.GetType() == typeof(Button))
                    ((System.Windows.Forms.Button)ctrl).Enabled = false;
        }

        public static void ShowForm(Form sourceForm, Label senderLabel, Form targetForm)
        {
            if (targetForm != null)
            {
                ToggleButtons(false, senderLabel);
                targetForm.ShowDialog();    
                Terminal.SetActivatedForm(sourceForm);
                ToggleButtons(true, senderLabel);
            }
        }

        static string senderLabel = string.Empty;
        private static void ToggleButtons(bool Enabled, Label SenderLabel)
        {
            if (!Enabled)
            {
                senderLabel = SenderLabel.Text;
                SenderLabel.Text = "Yükleniyor...";
            }
            else
                SenderLabel.Text = senderLabel;
        }

        public static ceTerminal.ceTerminal.ceTerminal ceWS;

        public static barkodTipleri BarkodTipi(int barcode)
        {
            if (barcode < 1e9) { return barkodTipleri.Top; }
            else if (barcode >= 1e9 && barcode < 2e9) { return barkodTipleri.RafAraba; }
            else if (barcode >= 2e9 && barcode < 3e9) { return barkodTipleri.CikisEmri; }
            else if (barcode >= 3e9 && barcode < 4e9) { return barkodTipleri.GelisPartisi; }

            return barkodTipleri.Tanimsiz;
        }

        public void ShowException(string info, string caption, Exception ex)
        {
            Terminal.PlayFail();
            MessageBox.Show(info != "Veritabanı hatası!" ? info :
                (ex.ToString().Substring(0, ex.ToString().IndexOf("-->") > -1 ? ex.ToString().IndexOf("-->") - 1 : ex.ToString().Length)),
                caption,
                MessageBoxButtons.OK,
                MessageBoxIcon.Exclamation,
                MessageBoxDefaultButton.Button1);
        }

        public static void ShowException(Exception ex)
        {
            Terminal.PlayFail();
            MessageBox.Show(
                (ex.ToString().Substring(0, ex.ToString().IndexOf("-->") > -1 ? ex.ToString().IndexOf("-->") - 1 : ex.ToString().Length)),
                "Hata",
                MessageBoxButtons.OK,
                MessageBoxIcon.Exclamation,
                MessageBoxDefaultButton.Button1);
        }

        public static DialogResult AskYesNo(string info, string caption)
        {
            Terminal.PlayFail();
            return MessageBox.Show(info, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
        }

        private void power_ValueChanged(object sender, EventArgs e)
        {
            action = Action.SetPower;
            Terminal.StopRFID();    //GetReply çağrılsın diye!
        }


        //private void power_ValueChanged(object sender, EventArgs e)
        //{
        //    Terminal.StopRFID();
        //    Terminal.RFID.SET_PowerControl((uint)power.Value);
        //}





        public static void CleanBarcode(ref string barcode, string TypeName)
        {
            //Code 39: Lufeng barkodu
            if ((Settings.TerminalId == 2 || Settings.TerminalId == 3) && TypeName != "Code 39")
                barcode = barcode.Substring(0, barcode.Length - 1);
            if (Settings.TerminalId == 1 && TypeName == "EAN 8")
                barcode = barcode.Substring(0, barcode.Length - 1);
        }

        /*
                public static int intParse(object x)
                {
                    //try
                    if(isPosInteger(x.ToString()))
                    {
                        return intParse(x.ToString());
                        //return Convert.ToInt32(str);
                    }
                    //catch
                    else
                    {
                        return 0;
                    }
                }
                */

        public static int intParse(object x)
        {
            string s = x.ToString().TrimStart("0".ToCharArray());
            if(s.Length>10)
                return 0;

            Regex rx = new Regex(@"^\d+$");
            if (rx.IsMatch(x.ToString()))
                return int.Parse(x.ToString());
            else
                return 0;
        }

        public static Int64 int64Parse(object x)
        {
            string s = x.ToString().TrimStart("0".ToCharArray());
            Regex rx = new Regex(@"^\d+$");
            if (rx.IsMatch(x.ToString()))
                return Int64.Parse(x.ToString());
            else
                return 0;
        }

        public int iTag(TreeNode tn)
        {
            if (tn.Tag != null)
                return intParse(tn.Tag.ToString());
            else
                return 0;
        }

        public int iText(TreeNode tn)
        {
            return intParse(tn.Text);
        }

        public Dictionary<int, int> images = new Dictionary<int, int>();
        public Dictionary<int, string> names = new Dictionary<int, string>();
        public Dictionary<int, double> EnYakinTop = new Dictionary<int, double>();


        
            //System.Diagnostics.Debug.WriteLine(treeNode.Text);
        
        TreeNode tx;
        private void FindNode(TreeNode treeNode, string rId)
        {

            if (treeNode.Text == rId)
                tx = treeNode;
            else if (treeNode.Nodes.Count > 0)
                foreach (TreeNode tn in treeNode.Nodes)
                    FindNode(tn, rId);
        }

        public void SwapNodes(TreeNode tn1, TreeNode tn2, int rId)
        {
            tx = null;
            FindNode(tn1, rId.ToString());
            if (tx != null)
            {
                TopYerlestir(tn2, rId);
                tx.Remove();

                //do
                //{
                //    TreeNode t = tx.Parent;
                //    tx.Remove();
                //    tx = t;
                //}
                //while (tx.Parent != tn1 && tx.Parent.Nodes.Count == 1);
            }

        }


        public void TopYerlestir(TreeNode tn, int RollId)
        {
            TreeNode tTop = tn.Nodes.Add(RollId.ToString());
            tTop.Tag = RollId;
        }
    }

}